package com.hp.btc.util.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendFileByFTP {

	private static final Logger logger = LoggerFactory.getLogger(SendFileByFTP.class);

	public static int BUFFER_SIZE = 10240;
	private FTPClient clientFTP = null;

	
	public SendFileByFTP(){}
	
	public SendFileByFTP(String user, String pass, String hostName) {
		this(user, pass, hostName, "21");
		logger.debug("SendFileByFTP FT = "+user+" "+pass+" "+hostName);
	}
	
	public SendFileByFTP(String user, String pass, String hostName, String port){
		logger.debug("SendFile FTP = "+user+" "+pass+" "+hostName+" "+port);
		try {
			createConnectionFTP(user, pass, hostName, Integer.parseInt(port));
		} catch (IOException e) {
			logger.error(" constructor SendFileByFTP " +e);
		}
	}
		
	
	public void sendFileData(String baseFolderFTP, File fileLocal) throws IOException{
		logger.debug("[sendFileData="+baseFolderFTP+"]");
		logger.debug("serverIsOpen == "+clientFTP.isConnected());
		clientFTP.enterLocalPassiveMode();
		clientFTP.changeWorkingDirectory(baseFolderFTP);
		clientFTP.setFileType(FTP.BINARY_FILE_TYPE);
		
		InputStream inputStream = new FileInputStream(fileLocal);
		boolean store = clientFTP.storeFile(fileLocal.getName(), inputStream);
		System.out.println(store);
		
        inputStream.close();
        
        logger.debug("Fin sendFileData ");
	}
	
	public void createConnectionFTP(String user, String pass, String hostName)
			throws IOException {
		createConnectionFTP(user, pass, hostName, 21);
	}

	public void createConnectionFTP(String user, String pass, String hostName,
			int port) throws IOException {
		clientFTP = new FTPClient();
		clientFTP.connect(hostName, port);
		clientFTP.login(user, pass);
		
	}
	
	public void close() throws IOException{
		try {
			clientFTP.logout();
			clientFTP.disconnect();
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (clientFTP.isConnected()) {
				try {
					clientFTP.logout();
					clientFTP.disconnect();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	public void renameFileFromFTP(String nameFile, String newNameFile) throws IOException{
		logger.debug("renameFileFromFTP="+nameFile +" " + newNameFile);
		logger.debug(""+clientFTP.pwd());
		clientFTP.rename(nameFile, newNameFile);
	}
		
}
